<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2019/5/22
 * Time: 15:44
 */
namespace app\admin\model;
use think\Db;
use think\Exception;

class DataBases{
    protected $name = '';
    protected $field = [];

    /**设置表名称
     * @param null $tablename
     * @return $this
     */
    public function setTableName($tablename=null){
        if($tablename){
            $this->name = $tablename;
        }
        return $this;
    }

    /**获取表名称
     * @return string
     */
    public function getTableName(){
        return $this->name;
    }

    /**设置
     * @param array $field
     * @return $this
     */
    public function setField($field=[]){
        if($field){
            $this->field = $field;
        }
        return $this;
    }

    /**获取字段
     * @return array
     */
    public function getField(){
        return $this->field;
    }

    /**添加表
     * @param array $data
     * @return bool
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function addTableAll($data=[]){
        if(empty($data)){
            return false;
        }
        if(!isset($data['model_table'])||!$data['model_table']){
            return false;
        }
        $this->setTableName(config('database.prefix').session('modular')."_".$data['model_table']);
        $this->addChangeModels(session('modular')."_".$data['model_table']);
        $modelid = $this->addModel($data);
        $this->addField($data['model_type'],$modelid);
        $this->addTable($data['model_type'],$data['table_engine']);
        Subject::addLianBiaoJur(['model_id'=>$modelid]);
        return true;
    }

    /**添加字段
     * @param $type
     * @param $modelid
     * @return bool
     * @throws \Exception
     */
    public function addField($type,$modelid){
        if($type=='单表模型'){
            $array =[
                [
                    'field_name'=>'栏目',
                    'field'=>'cid',
                    'type'=>'varchar',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'单行文本',
                    'sort'=>1000,
                    'defaults'=>'',
                    'delete'=>0
                ],
                [
                    'field_name'=>'名称',
                    'field'=>'name',
                    'type'=>'varchar',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'单行文本',
                    'sort'=>1000,
                    'defaults'=>'',
                    'delete'=>0
                ],
                [
                    'field_name'=>'描述',
                    'field'=>'dir',
                    'type'=>'varchar',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'单行文本',
                    'sort'=>1000,
                    'defaults'=>'',
                    'delete'=>0
                ],[
                    'field_name'=>'排序',
                    'field'=>'sort',
                    'type'=>'int',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'单行文本',
                    'sort'=>1008,
                    'defaults'=>100,
                    'delete'=>0
                ],
                [
                    'field_name'=>'创建时间',
                    'field'=>'create_time',
                    'type'=>'int',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'时间',
                    'sort'=>1006,
                    'defaults'=>0,
                    'delete'=>0
                ],
                [
                    'field_name'=>'更新时间',
                    'field'=>'update_time',
                    'type'=>'int',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'时间',
                    'sort'=>1005,
                    'defaults'=>1,
                    'delete'=>0
                ],
                [
                    'field_name'=>'是否可删除',
                    'field'=>'delete',
                    'type'=>'int',
                    'lang'=>1,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'状态',
                    'sort'=>10,
                    'defaults'=>1,
                    'delete'=>0
                ],
                [
                    'field_name'=>'状态',
                    'field'=>'status',
                    'type'=>'int',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'开关',
                    'sort'=>10,
                    'defaults'=>1,
                    'delete'=>0
                ]
            ];
        }else{
            $array = [
                [
                    'field_name'=>'名称',
                    'field'=>'name',
                    'type'=>'varchar',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'单行文本',
                    'sort'=>1010,
                    'defaults'=>'',
                    'delete'=>0
                ],
                [
                    'field_name'=>'上级',
                    'field'=>'pid',
                    'type'=>'varchar',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'下拉框',
                    'sort'=>1009,
                    'defaults'=>0,
                    'delete'=>0
                ],
                [
                    'field_name'=>'排序',
                    'field'=>'sort',
                    'type'=>'int',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'单行文本',
                    'sort'=>1008,
                    'defaults'=>100,
                    'delete'=>0
                ],
                [
                    'field_name'=>'图标',
                    'field'=>'tubiao',
                    'type'=>'varchar',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'单图片',
                    'sort'=>1007,
                    'defaults'=>'',
                    'delete'=>0
                ],
                [
                    'field_name'=>'创建时间',
                        'field'=>'create_time',
                    'type'=>'int',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'时间',
                    'sort'=>1006,
                    'defaults'=>0,
                    'delete'=>0
                ],
                [
                    'field_name'=>'是否可删除',
                    'field'=>'delete',
                    'type'=>'int',
                    'lang'=>1,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'状态',
                    'sort'=>10,
                    'defaults'=>1,
                    'delete'=>0
                ],
                [
                    'field_name'=>'状态',
                    'field'=>'status',
                    'type'=>'int',
                    'lang'=>255,
                    'option'=>'',
                    'table'=>'',
                    'status'=>1,
                    'model_id'=>$modelid,
                    'form_type'=>'开关',
                    'sort'=>10,
                    'defaults'=>1,
                    'delete'=>0
                ]
            ];
        }
        $field = new Fields();
        $field->allowField(true)->saveAll($array);
        return true;
    }

    /**添加模型
     * @param array $data
     * @return bool|mixed
     */
    public function addModel($data=[]){
        if(empty($data)){
            return false;
        }
        $data['create_time'] = time();
        $data['model_table'] = session('modular').'_'.$data['model_table'];
        $data['status'] = 1;
        $model = new Models();
        $model->allowField(true)->save($data);
        return $model->id;
    }

    /**添加表
     * @param $type
     * @param string $engine
     * @return bool
     */
    public function addTable($type,$engine='innodb'){
        $table = $this->getTableName();
        if($type=='单表模型'){
            $sql ="CREATE TABLE $table (id int(255) auto_increment primary key,`name` varchar(255) default '',`dir` varchar(255) default '',`cid` int(255) default null,`sort` int(255) default 100,`create_time` int(255) default 0,`update_time` int(255) default 0,`status` int(1) default '1',delete_time int(50) default null,`delete` int(1) default 1";
        }else{
            $sql = "create table $table (id int(255) auto_increment primary key,name varchar(255) default '',pid int(255) default 0,sort int(255) default 100,tubiao varchar(255) default '',create_time int(255) default 0,`delete` int(1) default 0,status int(1) default 1,delete_time int(50) default null";
        }
        $sql = $sql.")engine=$engine";
        try{
            Db::execute($sql);
            return true;
        }catch (\ErrorException $e){
            return false;
        }
    }

    /**删除所有模型
     * @param $id
     * @return bool
     * @throws Exception
     */
    public function delAll($id){
        if(is_array($id)){
            foreach ($id as $value){
                $this->del($value);
            }
        }else{
                $this->del($id);
        }
        return true;
    }

    /**删除所有模型
     * @param $id
     * @return bool
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del($id){
        if(!$id){
            return false;
        }
        $data = Models::where('id',$id)->findOrEmpty()->toArray();
        $this->delModels($data['model_table']);
        $tablename = config('database.prefix').$data['model_table'];
        $sql ="drop table $tablename";
        try{
            Fields::where('model_id',$id)->delete(true);
            Models::destroy($id,true);
            Db::execute($sql);
        }catch (Exception $e){
           throw new Exception('删除失败');
        }
        return true;
    }

    /**删除模型
     * @param $name
     */
    public function delModels($name){
        $name = explode('_',$name);
        $str = '';
        foreach ($name as $value){
            $str.=ucwords($value);
        }
        if(is_file('../application/'.session('modular').'/model/'.$str.'.php')){
            chmod('../application/'.session('modular').'/model/'.$str.'.php',0777);
            unlink('../application/'.session('modular').'/model/'.$str.'.php');
        }
    }

    /**添加表字段
     * @param array $array
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addFields($array=[]){
        $model = Models::where('id',$array['model_id'])->findOrEmpty()->toArray();
        $name = $array['field'];
        $type = $array['type'];
        $lang = $array['lang'];
        $defult = $array['defaults'];
        $table = config('database.prefix').$model['model_table'];
        if($type=='float'||$type=='FLOAT'){
            $sql = "alter table $table add `$name` $type(".$lang.",2) default '".$defult."'";
        }else{
            if($type=='text'){
                $sql = "alter table $table add `$name` $type(".$lang.")";
            }else{
                $sql = "alter table $table add `$name` $type(".$lang.") default '".$defult."'";
            }
        }
        try{
            Db::execute($sql);
        }catch (Exception $e){
            return false;
        }
        return true;
    }

    /**修改字段
     * @param array $array
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeField($array=[]){
        $model = Models::where('id',$array['model_id'])->findOrEmpty()->toArray();
        $field = Fields::where('id',$array['id'])->findOrEmpty()->toArray();
        $name = '';
        if($field){
            $name = $field['field'];
        }
        $table = config('database.prefix').$model['model_table'];
        $type  = $array['type'];
        $lang  = $array['lang'];
        $defult = $array['defaults'];
        $newname = $name;
        if($array['type']=='float'){
            $sql = "alter table $table change `$name` `$newname` $type($lang,2) default `$defult`";
        }else{
            if($type=='text'){
                $sql = "alter table $table change `$name` `$newname` $type($lang)";
            }else{
                $sql = "alter table $table change `$name` `$newname` $type($lang) default '".$defult."'";
            }
        }
//        echo $sql;exit;
        try{
            Db::execute($sql);
        }catch (ErrorException $e){
            return false;
        }
        return true;
    }

    /**删除字段
     * @param $id
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delField($id){
        $field = Fields::where('id',$id)->findOrEmpty()->toArray();
        if($field){
            $model = Models::where('id',$field['model_id'])->findOrEmpty()->toArray();
            $name = $field['field'];
            if($model){
                $table = config('database.prefix').$model['model_table'];
                $sql = "alter table $table drop column $name";
                try{
                    Db::execute($sql);
                }catch (Exception $e){
                    return false;
                }
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    /**添加模型
     * @param $name
     */
    public function addChangeModels($name){
        $modelname = $name;
        $name = explode('_',$name);
        $str = '';
        foreach ($name as $key=>$value){
            if($key!==0){
                $str .= ucwords($value);
            }
        }
        $url = '../application/'.session('modular').'/model';
        if(!is_dir($url)){
            chmod('../application',0777);
            mkdir($url,true);
        }
        $newstr = '<?php
/**
 * Created by PhpStorm.
 * User: 毛文科
 * Date: 2019/5/24
 * Time: 10:49
 */
namespace app\\'.session('modular').'\\model;
use think\Model;
use think\model\concern\SoftDelete;

class '.$str.' extends Model
{
    protected $name = "'.$modelname.'";
    protected $pk = "id";
    use SoftDelete;
    protected $deleteTime = "delete_time";
}';
        chmod($url,0777);
        file_put_contents($url.'/'.$str.'.php',$newstr);
    }

}